package servlet;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.RequestToBean;
import action.Action;
import bean.XmlBean;
import form.ActionForm;

public class ActionServlet extends HttpServlet {


	public ActionServlet() {
		super();
	}

	
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	this.doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	request.setCharacterEncoding("UTF-8");
	String requestUrl=request.getServletPath().split("\\.")[0];
	Map<String,XmlBean> xmlMap=(Map<String,XmlBean>)this.getServletContext().getAttribute("xmlMap");
	XmlBean xmlBean=xmlMap.get(requestUrl);
	Action action=null;
	String forwardUrl=null;
	try {
		Class clazz = Class.forName(xmlBean.getActionClass());
		
		action = (Action) clazz.newInstance();
		ActionForm actionForm=RequestToBean.fill(xmlBean.getFormClass(), request); 
		forwardUrl=xmlBean.getActionForward().get(action.execute(request, response, actionForm));
		request.getRequestDispatcher(forwardUrl).forward(request, response);
	} catch (Exception e) {
		e.printStackTrace();
	}

	
	}

	

	public void init() throws ServletException {
		// Put your code here
	}

}
